package com.fat.spzx.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.fat.spzx.common.exception.GlobalException;
import com.fat.spzx.manager.listener.CategoryEasyExcelListener;
import com.fat.spzx.manager.mapper.CategoryMapper;
import com.fat.spzx.manager.service.CategoryService;
import com.fat.spzx.model.entity.product.Category;
import com.fat.spzx.model.vo.common.ResultCodeEnum;
import com.fat.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        //1.根据parentId查询
        List<Category> categoryList = categoryMapper.selectByParentId(parentId);
        //2.判断当前是否有子节点
        if(!CollectionUtil.isEmpty(categoryList)){
            categoryList = categoryList.stream().map(category -> {
                //3.有子节点，则查询子节点是否有子节点
                int count = categoryMapper.selectByParentIdWithCount(category.getId());
                //4.如果有子节点，则设置为true
                if (count > 0){
                    category.setHasChildren(true);
                }
                return category;
            }).collect(Collectors.toList());
        }
        //4.返回结果
        return categoryList;
    }

    /**
     * 导出数据
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 查询数据库中的数据
            List<Category> categoryList = categoryMapper.selectAll();

            //处理数据
            List<CategoryExcelVo> categoryExcelVoList = categoryList.stream().map(category -> {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo);
                return categoryExcelVo;
            }).toList();

            // 导出数据
            EasyExcel.write(response.getOutputStream(),CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 导入数据
     */
    @Override
    public void importData(MultipartFile file) {
        try {
            CategoryEasyExcelListener<CategoryExcelVo> listener = new CategoryEasyExcelListener<>(categoryMapper);
            EasyExcel.read(
                    file.getInputStream(),
                    CategoryExcelVo.class,
                    listener)
                    .sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
            throw new GlobalException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
